package com.jrx.anytxn.transaction.job.dailyAccount.step;

import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.entity.BtDailyAccountList;
import com.jrx.anytxn.transaction.entity.TlDailyAccountLog;
import com.jrx.anytxn.transaction.entity.TlDisbursementLog;
import com.jrx.anytxn.transaction.mapper.ext.ExtTlDailyAccountLogMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * 日终T24核心汇总记账初始化
 *
 * @Author yhy
 * @Date 2023/4/29 9:20
 */
@Service
public class DailyAccountInitProcessor implements ItemProcessor<TlDisbursementLog, BtDailyAccountList> {

    private final Logger logger = LoggerFactory.getLogger(DailyAccountInitProcessor.class);

    @Resource
    private ExtTlDailyAccountLogMapper extTlDailyAccountLogMapper;


    @Override
    public BtDailyAccountList process(TlDisbursementLog item) throws Exception {

        try {
            // 退汇、抹账、取消等
            if (TransBizConstant.DISBURSEMENT_LOG_SUM_STATUS_F.equalsIgnoreCase(item.getSumStatus())) {
                // 如果都是同一天则不需要进行T24日终汇总，否则负数的金额会变大
                if (DateUtils.sameDate(item.getBusinessDate().getTime(), item.getCollateDate().getTime())) {
                    return null;
                } else {
                    // 非同一天的则需要进一步判断是否已经有过正向的汇总过
                    // ①如果没有正向的汇总过，则无需处理；②如果已有正向的，需要一个逆向的汇总
                    List<TlDailyAccountLog> logs = extTlDailyAccountLogMapper.queryDailyAccountLog(item.getTenantId(), item.getCustomerId(), item.getLoanId(), item.getProductId(),
                            TransBizConstant.DISBURSEMENT_LOG_SUM_STATUS_S);
                    // 有正向的汇总
                    boolean forward = logs.stream().anyMatch(log -> log.getAmount().compareTo(BigDecimal.ZERO) > 0);
                    // 且没有逆向汇总
                    boolean reverse = logs.stream().anyMatch(log -> log.getAmount().compareTo(BigDecimal.ZERO) < 0);
                    // 有正向的且没有逆向的汇总
                    if (!(forward && !reverse)) {
                        return null;
                    }
                }
            }
            BtDailyAccountList btDailyAccountList = new BtDailyAccountList();
            // 主键Id
            btDailyAccountList.setId(item.getId());
            // 租戶id
            btDailyAccountList.setTenantId(item.getTenantId());
            // 机构号
            btDailyAccountList.setOrganizationId(item.getOrganizationId());
            // 渠道
            btDailyAccountList.setChannel(item.getChannel());
            // 产品id
            btDailyAccountList.setProductId(item.getProductId());
            // 客户id
            btDailyAccountList.setCustomerId(item.getCustomerId());
            // 流水号
            btDailyAccountList.setSeqNo(item.getSeqNo());
            // 贷款订单id
            btDailyAccountList.setLoanId(item.getLoanId());
            // 记账金额
            btDailyAccountList.setAmount(item.getAmount());
            // 放款最终状态为F-失败，则记账金额取反
            if (TransBizConstant.DISBURSEMENT_LOG_SUM_STATUS_F.equals(item.getSumStatus())){
                // 记账金额
                btDailyAccountList.setAmount(item.getAmount().negate());
            }
            // 支付通道 BEPS-小额;HVPS-大额;IBPS-网银清算;
            btDailyAccountList.setSettleChannel(item.getSettleChannel());
            btDailyAccountList.setUpdateBy(TransBizConstant.SYS_OPRATE);
            btDailyAccountList.setRecordVersionNumber(TransBizConstant.INIT_RECORD_VERSION_NUMBER);
            return btDailyAccountList;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("DailyAccountInitProcessor 出错了：{}", e);
        }
        return null;
    }
}

